package com.bkhc.umc.auth.handler;

import com.bkhc.umc.entity.ApiInfo;
import com.bkhc.umc.repository.ApiInfoRepository;
import com.bkhc.umc.filter.AuthenticationFilter;
import com.bkhc.umc.repository.RoleRepository;
import com.bkhc.umc.service.ApiInfoSerivce;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.ObjectPostProcessor;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.security.web.access.intercept.FilterSecurityInterceptor;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.util.CollectionUtils;

import java.util.List;

/**
 * @EnableWebSecurity注解继承WebSecurityConfigurerAdapter的类，这样就构成了Spring Security的配置。
 *
 */
@EnableWebSecurity
@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
@Order(1)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {


    private final AuthenticationFailEntryPoint unauthorizedHandler;

    private final AccessDeniedHandler accessDeniedHandler;

    private final UserDetailsService userAuthService;

    private final AuthenticationFilter authenticationTokenFilter;

    private final AccessDecisionManager customAccessDecisionManager;

    private WebSecurity web;

    @Autowired
    private ApiInfoSerivce apiInfoSerivce;

    private final FilterInvocationSecurityMetadataSource customFilterInvocationSecurityMetadataSource;
    @Autowired
    public WebSecurityConfig(AuthenticationFailEntryPoint unauthorizedHandler,
                             AccessDeniedHandler accessDeniedHandler,
                             UserDetailsService userAuthService,
                             AuthenticationFilter authenticationTokenFilter,
                             AccessDecisionManager customAccessDecisionManager,
                             FilterInvocationSecurityMetadataSource customFilterInvocationSecurityMetadataSource,
                             ApiInfoSerivce apiInfoSerivce) {
        this.unauthorizedHandler = unauthorizedHandler;
        this.accessDeniedHandler = accessDeniedHandler;
        this.userAuthService = userAuthService;
        this.authenticationTokenFilter = authenticationTokenFilter;
        this.customAccessDecisionManager = customAccessDecisionManager;
        this.customFilterInvocationSecurityMetadataSource = customFilterInvocationSecurityMetadataSource;
    }

    @Autowired
    public void configureAuthentication(AuthenticationManagerBuilder authenticationManagerBuilder) throws Exception {
        authenticationManagerBuilder
                // 设置UserDetailsService
                .userDetailsService(this.userAuthService)
                // 使用BCrypt进行密码的hash
                .passwordEncoder(passwordEncoder());
    }

    /**
     * 装载BCrypt密码编码器
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity httpSecurity) throws Exception {
        httpSecurity.authorizeRequests()
                .withObjectPostProcessor(new ObjectPostProcessor<FilterSecurityInterceptor>() {
            @Override
            public <O extends FilterSecurityInterceptor> O postProcess(O o) {
                o.setSecurityMetadataSource(customFilterInvocationSecurityMetadataSource);
                o.setAccessDecisionManager(customAccessDecisionManager);
                return o;
            }
        })
                .and()

                .exceptionHandling().accessDeniedHandler(accessDeniedHandler).and()

                .csrf().disable()
                .exceptionHandling().authenticationEntryPoint(unauthorizedHandler).and()

//                .authorizeRequests()
//
//                // 允许匿名访问
//                .antMatchers("/login/in").permitAll()
//                // 除上面外的所有请求全部需要鉴权认证
//                .and()
                .authorizeRequests()
                .anyRequest().authenticated();


        // 禁用缓存
        httpSecurity.headers().cacheControl();

        httpSecurity
                .addFilterBefore(authenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
    }

    @Override
    public void configure(WebSecurity web) {
        web
                .ignoring()
                .antMatchers(
                        "swagger-ui.html",
                        "**/swagger-ui.html",
                        "/favicon.ico",
                        "/**/*.css",
                        "/**/*.js",
                        "/**/*.png",
                        "/**/*.gif",
                        "/swagger-resources/**",
                        "/v2/**",
                        "/**/*.ttf",
                        "/login/in",
                        "/role/query"
                );
        List<ApiInfo> apis = apiInfoSerivce.getCommonApi();
        if(!CollectionUtils.isEmpty(apis)){
            for(ApiInfo api:apis){
                web
                        .ignoring()
                        .antMatchers(api.getApi());
            }

        }

    }

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }
}